

$(document).ready(function() {
	datatablePlugins();
	//iniClientForm();
	iniClientDatatable();
});


/**
 * this function is added to the prototype of datatable plugin so we can reload 
 * data from server and use the local search feacture (avoiding this way the use of the server by the search field)
 */
function datatablePlugins() {
	
	// fnReloadAjax
	$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
	{
	    if ( typeof sNewSource != 'undefined' && sNewSource != null )
	    {
	        oSettings.sAjaxSource = sNewSource;
	    }
	    this.oApi._fnProcessingDisplay( oSettings, true );
	    var that = this;
	    var iStart = oSettings._iDisplayStart;
	    var aData = [];
	 
	    this.oApi._fnServerParams( oSettings, aData );
	     
	    oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
	        /* Clear the old information from the table */
	        that.oApi._fnClearTable( oSettings );
	         
	        /* Got the data - add it to the table */
	        var aData =  (oSettings.sAjaxDataProp !== "") ?
	            that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
	         
	        for ( var i=0 ; i<aData.length ; i++ )
	        {
	            that.oApi._fnAddData( oSettings, aData[i] );
	        }
	         
	        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
	        that.fnDraw();
	         
	        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
	        {
	            oSettings._iDisplayStart = iStart;
	            that.fnDraw( false );
	        }
	         
	        that.oApi._fnProcessingDisplay( oSettings, false );
	         
	        /* Callback user function - for event handlers etc */
	        if ( typeof fnCallback == 'function' && fnCallback != null )
	        {
	            fnCallback( oSettings );
	        }
	    }, oSettings );
	};
}


function iniClientForm() {
	
	var serverRequest = window.ajaxUrl + '/tmp?tmp=val';
	
	var clientBirthday = $("#clientBirthday");
	
	clientBirthday.datepicker({
		showButtonPanel: 	true,
		changeMonth: 		true,
		changeYear: 		true,
		dateFormat: 		'yy-mm-dd',
		//dateFormat: 		'@',
		//showAnim:			'fade',
		defaultDate:		'1980-07-07',
		yearRange: 			'1920:2012',
		//currentText: 'Now'
		onSelect:			function() {
			//clientBirthday.addClass('validate[required,custom[date]] text-input datepicker');
			//$.validationEngine.loadValidation(clientBirthday);
			//clientBirthday.blur(function () {
				//$.validationEngine.loadValidation(clientBirthday);
			//});
		}
	});
	
	var	remoteAutoCompleteOptions = {
		source: 	serverRequest,
		scroll:		false,
		delay: 		'500',
		minLenght: 	2,
		select: 	function(event,ui) {
			
		}
	};

	var localAutoCompleteOtpions = {
		source: ['adriano','antonio','maria','carla','sandra'],
		select: function(event,ui) {
			console.log(event);
			console.log(ui);
		}
	};

	var clientForm 			= $('#clientForm'); 
	var clientName 			= $('input#clientName');
	var clientEmail 		= $('input#clientEmail');

	// default validationEngine options
	var validationOptions = {
		promptPosition:		"centerRight", 
		scroll: 			true,
		autoHidePrompt:		true,
		autoHideDelay:		2000,
		onValidationComplete:			function(form, status) {
		}
	};
	
	clientForm.validationEngine(validationOptions);

	// show infromation about the red star near the label
	$('.formee-req').on('click',function() {
		$(this).validationEngine('showPrompt','campo obrigatório','red');
	});
	
	// autocomplete
	//clientName.autocomplete(tmpProperties);
	//clientName.autocomplete(remoteAutoCompleteOptions);
	//clientName.autocomplete(tmpProperties);
	
}





function iniClientDatatable() {
	
	// feed the datatable from this link
	var serverRequest = window.ajaxUrl + '/readClientAction';
	
	var clientTable = $('#clientTable');

	// datatable options 
	var tableProperties = {
		'sDom':				"<'row'<'span8'l><'span4'f>r>t<'row'<'span8'i><'span4'p>>", // bootstrap intregation
		'sAjaxSource': 		serverRequest,	
		'sServerMethod':	'POST',
		'sAjaxDataProp': 	'data',
		'fnServerParams': 	function (aoData) {
				aoData.push( {'var1':'value1','var2':'value2'});
		},
		"aoColumns": [
			{"mDataProp":"name"},
			{"mDataProp":"address"},
			{"mDataProp":"email"},
			{"mDataProp":"phone"},
			{"mDataProp":"birthday"}
		],
		//'sPaginationType': "bootstrap", // ... need a plugin to work
		'bJQueryUI':		false,	// enable jqueryUI Themes
		'bPaginate':		true,
		'bSort':			true,
		'bInfo':			true,
		'bAutoWidth':		true,
		'bProcessing': 		true,
		'bServerSide': 		false,	// use server side processing
		'oLanguage': {
			'sInfo':		'registos _START_ até ao _END_ de _TOTAL_',
			'sZeroRecords': 'Não existem registos',
			'sSearch':		'Procurar',
			'sLengthMenu':	'Mostrar <select>' +
				'<option value="5">5</option>'+
				'<option value="10">10</option>'+
		        '<option value="20">20</option>'+
		        '<option value="30">30</option>'+
		        '<option value="40">40</option>'+
		        '<option value="50">50</option>'+
		        '<option value="-1">Todos</option>'+
		        '</select> registos'
		}	
	};

	// set datatable options
	clientTable.dataTable(tableProperties);
	
	// CLICK EVENTS
	clientTable.find('tbody tr').live('click',function() {

		// get data from the selected row
		clientData = clientTable.fnGetData(this); console.log(clientData);
		
		// break here if there is no client in the table
		if ( !clientData )
			return;
		
		if ( $(this).hasClass('row_selected') ) { // ... the row is already selected
			
            $(this).removeClass('row_selected'); 
            
            // reset clientForm
            //clearClientForm();
		} 
		else { // ... no row selected
			
	        // avoid multi selected row ... 
           	clientTable.$('tr.row_selected').removeClass('row_selected');
           	
           	// highlight selected row
            $(this).addClass('row_selected');
            
            // change button label
           	//createButton.html('Atualizar'); 
           	
            // set the client id
			//clientForm.attr('data-id',clientData.id);
			
			// fill form with all client info
            /*
			clientForm.find('#clientName input').val(clientData.name).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientAddress input').val(clientData.address).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientEmail input').val(clientData.email).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientPhone input').val(clientData.phone).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientHeight input').val(clientData.height).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientBirthday input').val(clientData.birthday).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientWeight input').val(clientData.weight).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientSex select').val(clientData.sex);
			clientForm.find('#clientNationality input').val(clientData.nationality).next().html('').parents('.control-group').attr('class','control-group success');
			clientForm.find('#clientInfo textarea').val(clientData.info);
			*/
		}
	});
}


